package com.gxc.authcore.client.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import com.gxc.authcore.system.util.ParamUtil;
import com.gxc.authcore.system.util.SerializeUtil;
import com.gxc.webcore.util.RequestUtil;
import com.gxc.webcore.util.StringUtil;

@Controller("common/authclientController")
public class AuthClientController {

	/**
	 * 客户端调用，重定向至认证中心，获取authid
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView redirectToAuth(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 重定向
		response.sendRedirect(ParamUtil.get("url_authcenter")
				+ "/common/authserver/getAuthId.do"
				+ SerializeUtil.serializeRedirectParam(request));

		return null;
	}

	/**
	 * 客户端调用，设置authid，并跳转至之前访问的url
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public ModelAndView setAuthId(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map params = RequestUtil.getInMap(request);
		// 设置authid
		String authid = request.getParameter("authid");
		if (!StringUtil.isTrimEmpty(authid)) {
			authid = authid.trim();
			HttpSession session = request.getSession();
			session.setAttribute("authid", authid);

			// TODO P3P
			String p3p = "CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"";
			response.addHeader("P3P", p3p);

			// 重定向至之前访问的url
			String clientRequestUrl = request.getParameter("clientRequestUrl");
			params.remove("clientRequestUrl");
			params.remove("clientSystemUrl");
			params.remove("authid");
			response.sendRedirect(clientRequestUrl
					+ SerializeUtil.serializeParam(params));
		} else {
			// 重定向至登陆页面
			String loginUrl = ParamUtil.get("url_authcenter")
					+ "/common/auth/login.do";
			response.sendRedirect(loginUrl
					+ SerializeUtil.serializeParam(params));
		}

		return null;
	}

}
